using System;
using System.IO;
using System.CodeDom.Compiler;
using System.Collections.Specialized;

namespace SvnPmtHook
{
	public class SilentCaptureConsoleImpl : ICaptureConsole
	{
		public string Capture(string command)
		{
			string result = "";
			using (StringWriter writer = new StringWriter())
			{
				var lines = Execute(command);
				foreach (var line in lines)
				{
					if (String.IsNullOrEmpty(line.Replace(" ", "")))
						continue;

					writer.WriteLine(line);
				}
				result = writer.ToString();
			}
			return result;
		}


		/// <summary>
		/// Executes the specified command.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <returns></returns>
		/// <remarks>This code was extracted from this guys project: 
		/// http://chrison.net/SVNPostCommitHookV17.aspx</remarks>
		private StringCollection Execute(string command)
		{
			
			string output = "";
			string error = "";

			TempFileCollection tf = new TempFileCollection();
			Executor.ExecWaitWithCapture(command, tf, ref output, ref error);

			StreamReader sr = File.OpenText(output);
			StringCollection coll = new StringCollection();
			string strLine = null;

			sr.ReadLine(); // skip first line

			while (null != (strLine = sr.ReadLine()))
			{
				coll.Add(strLine);
			}
			sr.Close();

			File.Delete(output);
			File.Delete(error);

			return coll;
		}
	}
}
